package cn.com.zcode.user.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;

import cn.com.zcode.core.dao.BaseHibernateDaoSupport;
import cn.com.zcode.user.model.InviteCode;
import cn.com.zcode.user.model.User;

public class UserDaoImpl extends BaseHibernateDaoSupport implements UserDao {

	public User getUser(String username, String password) {
		User user = this.getByHQL("from User where username=? and password=?", User.class, username, password);
		return user;
	}

	@Override
	public User getUserById(String id) {
		return this.get(id, User.class);
	}

	@Override
	public User getUserByName(String name) {
		return this.getByHQL("from User where username=?", User.class, name);
	}

	@Override
	public boolean checkInviteCode(String codenum) {
		InviteCode code = this.getByHQL("from InviteCode where code = ? and disable = 0 and usedTime is null", InviteCode.class, codenum);
		return code != null;

	}

	@Override
	public void usedInviteCode(String uid, String code) {
		uid = uid.trim();
		Query query = this.getSession().createQuery("update InviteCode set uid =:uid ,usedTime =:usedTime  where code =:code");
		query.setString("uid", uid);
		query.setDate("usedTime", new Date());
		query.setString("code", code);
		query.executeUpdate();

	}

	@Override
	public List<InviteCode> listInviteCodes() {
		return this.findByHQL("from InviteCode where disable=0 and uid is null", InviteCode.class);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<User> findUsers(String[] userid) {
		Query query = this.getSession().createQuery("from User where id in (:ids)");
		query.setParameterList("ids", userid);

		return query.list();
	}

}
